<?php
class UsersController extends CController {
	public function actions() {
		return array(
			// Captcha action renders the CAPTCHA image
			'captcha' => array(
				'class' => 'CCaptchaAction',
				'backColor' => 0xF5F5F5,
				'foreColor' => 0x6C8D00,
				'maxLength' => 5,
				'minLength' => 5,
				'height' => 30
			)
		);
	}


	public function filters() {
		return array(
				'accessControl'
		);
	}

	public function accessRules() {
		return array(
			array(
				'allow',
				'actions' => array('*')
			),
			array(
				'deny',
				'actions' => array('editprofile', 'viewprofile', 'updateavatar', 'changepassword', 'myqas', 'subscribe'),
				'users' => array('?')
			)
		);
	}
	
	public function actionSignIn() {
		if(Users::isLogin()) {
			$this->redirect(Yii::app()->user->getReturnUrl());
		}

		$user = new ForumMembers;

		$msgs = array();
		if(isPost()) {
			$user->attributes = $_POST['ForumMembers'];
			$duration = 0;
			if(isset($_POST['isStayLoggedIn']) && $_POST['isStayLoggedIn'] == '1') {
				$duration = Yii::app()->params->stayLoggedInDuration;
			}
            if(($status = @$this->_login($user, $duration)) > 0) {
                $jumpTo = $this->getJumpTo();
                $this->setPageTitle('登陆成功，欢迎回来 - 广州心理咨询网');
                $this->render('signin-success', array('user' => $user, 'jumpTo' => $jumpTo));
                return ;
            } else {
                switch($status) {
                    case '-1':
                    case '-2':
                        $msgs[UserIdentity::ERROR_PASSWORD_INVALID] = '用户名或密码错误，请重新填写。';
                        break;
                }
            }
		}

		// Render to view
		Yii::app()->layout = 'layoutsUsers';
		$this->setPageTitle('用户登录 - 广州心理咨询网');
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/userSignIn.js', CClientScript::POS_END);
		$this->render('userSignIn', array(
				'user' => $user,
				'msgs' => $msgs,
			)
		);
	}

    protected function getJumpTo() {
        $ref = '';
        if(isset($_GET['rf'])) {
            // Hack............
            $ref = urldecode(urldecode(substr(Yii::app()->request->getPathInfo(), strpos(Yii::app()->request->getPathInfo(), '/rf')+strlen('/rf')+1)));
        }
        if(strstr(Yii::app()->user->getReturnUrl(), 'index.php') != 'index.php') {
            $jumpTo = Yii::app()->user->getReturnUrl();
        } else if($ref !== '' && strpos($ref, 'users/') !== 0) {
            if(strstr($ref, '.html/') != '.html/' && strstr($ref, '.html') != '.html') {
                $jumpTo = Yii::app()->request->getScriptUrl().'/'.$ref;
            } else {
                $jumpTo = Yii::app()->getBaseUrl().'/'.rtrim($ref, '/');
            }
        } else {
            $jumpTo = Yii::app()->getBaseUrl();
        }
        return $jumpTo;
    }
	
	public function actionSignOut() {
		if(Users::isLogin()) {
            Yii::app()->user->logout();
		}
        $this->setPageTitle('退出登录 - 广州心理咨询网');
        $this->render('logout', array('jumpTo' => $this->getJumpTo()));
	}

    private function _login(&$user, $duration = 0) {
    	// For encoding compatible
//        if( ! ctype_alpha($user->username)) {
//        	$loginStatus = uc_user_login(iconv('UTF-8', 'GBK', $user->username), $user->password);
//        } else {
//        	$loginStatus = uc_user_login($user->username, $user->password);
//        }

        $loginStatus = uc_user_login($user->convertUserNameEncoding(), $user->password);
        if($loginStatus[0] > 0) {
            $identity = new UserIdentity($user->username, $user->password);
            $user = ForumMembers::model()->findByUserName($user->username);
            $identity->authenticate();
            Yii::app()->user->login($identity, $duration);
        }
        return $loginStatus[0];
    }
    
	public function actionSignUp() {
		if(isPost() && isset($_POST['ForumMembers'])) {
			$user = new ForumMembers;
			$user->setScenario('signUp');
			$user->attributes = $_POST['ForumMembers'];

			$registerStatus = uc_user_register($user->convertUserNameEncoding(), $user->password, $user->email);
			if($registerStatus > 0) {
				$this->_login($user);
                sendMail($user->email, $user->username, '[广州心理咨询网]'.$user->userName().'，感谢您的注册，愿您能在本站获取所需。请阅读以下内容', $user->getRegisterMailText());
				// Redirect to index page
                if(strstr(Yii::app()->user->getReturnUrl(), 'index.php') != 'index.php') {
                    $jumpTo = Yii::app()->user->getReturnUrl();
                } else {
                    $jumpTo = CHtml::normalizeUrl(array('/users/viewprofile'));
                }
				$this->setPageTitle('注册成功，欢迎登录广州心理咨询网 - 广州心理咨询网');
				$this->render('signup-success', array('user' => $user, 'jumpTo' => $jumpTo));
				return ;
			}
		}
		
		$_user = new ForumMembers;
		// Initialize JavaScript global variables
		initJsVar();
		// Render to view
		Yii::app()->layout = 'layoutsUsers';
		$this->setPageTitle('用户注册 - 广州心理咨询网');
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/js/userSignUp.js', CClientScript::POS_END);
		$this->render('userSignUp', array(
			'user' => $_user
		));
	}

	public function actionViewprofile() {
		$userId = isset($_GET['id']) ? (int)$_GET['id'] : Yii::app()->user->id;

		$user = ForumMembers::model()->with(array('bbs', 'bbsMemberFields'))->findByPk($userId);
		if($user !== null) {
			$titlePrefix = $user->getIsSelf() ? '我的个人资料' : $user->username.' 的个人资料';
			$this->setPageTitle($titlePrefix.'_个人中心');
			$this->render('view', array(
					'user' => $user,
					'titlePrefix' => $titlePrefix
				)
			);
		} else {
			throw new CHttpException(404, '该用户不存在！');
		}
	}

    public function actionSubscribe() {
		$userId = Yii::app()->user->id;
		
		$user = ForumMembers::model()->findByPk($userId);
    	if($user !== null) {
    		if(isPost() && isset($_POST['ForumMembers'])) {
    			$user->subscribed = (int)$_POST['ForumMembers']['subscribed'];
    			$user->save();
    		}

			$this->setPageTitle('订阅《心灵智慧》_个人中心');
			$this->render('subscribed', array(
					'user' => $user
				)
			);
    	}
    }

	public function actionMyqas() {
		$userId = Yii::app()->user->id;
		
		$user = ForumMembers::model()->findByPk($userId);
		if($user !== null) {
			$criteria = new CDbCriteria;
			$criteria->condition = 'qaAuthor = '.$user->uid;
			$criteria->order = 'qaId DESC';
			$qas = QAs::model()->topic()->findAll($criteria);

			$this->setPageTitle('我的问吧提问 _个人中心');
			$this->render('my-qas', array('qas' => $qas));
		}
	}
	
	public function actionMypsytest() {
		if($userId = Users::isLogin()) {
			$user = ForumMembers::model()->findByPk((int)$userId);
			if($user !== null) {
				$criteria = new CDbCriteria;
				$criteria->condition = 'userId = '.$user->uid;
				$criteria->order = 'doneAt DESC';
				$psytestCount = UserPsytest::model()->with('topic', 'topic.category')->count($criteria);
				$pages = new CPagination($psytestCount);
				$pages->pageSize = 10;
				$pages->applyLimit($criteria);
				$userPsytests = UserPsytest::model()->with('topic', 'topic.category')->findAll($criteria);
	
				$this->setPageTitle('我的心理测试 _个人中心');
				$this->render('my-psytest', array('userPsytests' => $userPsytests, 'pages' => $pages));
			}
		}
	}
	
	public function actionEditprofile() {
		$userId = Yii::app()->user->id;
		
		$user = ForumMembers::model()->with(array('bbs', 'bbsMemberFields'))->findByPk($userId);
		if($user !== null) {
			if($user->bbs === null) {
				$user->bbs = new BbsMembers;
				$user->bbs->uid = $user->uid;
				$user->bbs->username = $user->username;
			} else {
				$user->bbs = $user->bbs;
			}
			if($user->bbsMemberFields === null) {
				$user->bbsMemberFields = new BbsMemberFields;
				$user->bbsMemberFields->uid = $user->uid;
			} else {
				$user->bbsMemberFields =  $user->bbsMemberFields;
			}

			if(isPost() && isset($_POST['BbsMembers']) && isset($_POST['BbsMemberFields'])) {
				$user->bbs->attributes = $_POST['BbsMembers'];
				$user->bbsMemberFields->attributes = $_POST['BbsMemberFields'];
				if($user->bbs->validate() && $user->bbsMemberFields->validate()) {
					$user->bbs->save(false);
					$user->bbsMemberFields->save(false);
				}
			}

			$this->setPageTitle('修改我的个人资料_个人中心');
			$this->render('edit', array(
					'user' => $user
				)
			);
		}
	}
	
	public function actionChangepassword() {
		$userId = Yii::app()->user->id;
		
		$user = ForumMembers::model()->findByPk($userId);
		if($user !== null) {
			$user->scenario = 'changePassword';
			$result = 0;
			if(isPost() && isset($_POST['ForumMembers'])) {
				$user->attributes = $_POST['ForumMembers'];
				$user->oldPassword = $_POST['ForumMembers']['oldPassword'];
				$user->password = $_POST['ForumMembers']['password'];
				$user->confirmPassword = $_POST['ForumMembers']['confirmPassword'];
				$user->validate();
				if( ! preg_match(ForumMembers::REGEXP_PASSWORD, $user->password)) {
					$user->addError('password', '密码格式有误。密码可由大小写英文字母、数字组成，长度6－20个字符。');
				}
				if( ! $user->hasErrors()) {
					$result = uc_user_edit($user->username, $user->oldPassword, $user->password, $user->email);
					if($result == -1) {
						$user->addError('password', '您输入的当前密码不正确，请检查后重新输入。');
					}
				}
			}
			$this->setPageTitle('修改密码_个人中心');
			$this->render('change-password', array(
					'user' => $user,
					'result' => $result
				)
			);
		}
	}
	
	public function actionUpdateavatar() {
		$userId = Yii::app()->user->id;
		
		$user = ForumMembers::model()->with(array('bbs', 'bbsMemberFields'))->findByPk($userId);
		if($user !== null) {
			$this->setPageTitle('修改头像_个人中心');
			$this->render('update-avatar', array(
					'user' => $user
				)
			);
		}
	}
	
	public function actionEmailExists() {
		if(isAjax()) {
			$userEmail = $_POST['email'];
			echo uc_user_checkemail($userEmail);
		}
	}

    public function actionCheckUserName() {
        if(isAjax()) {
			$user = new ForumMembers;
            $user->username = $_POST['username'];
            echo uc_user_checkname($user->convertUserNameEncoding());
        }
    }

	public function actionResetPassword() {
		$user = new ForumMembers;
		
		if(isPost()) {
			if(isset($_GET['email']) && isset($_GET['encoded']) && isset($_GET['username'])) {
				$_user = ForumMembers::model()->find('username = ? AND email = ?', array(urldecode($_GET['username']), urldecode($_GET['email'])));
				$_user->scenario = 'resetPassword';
				if($_user !== null && Yii::app()->user->id != $_user->uid) {
					if($_GET['encoded'] == md5($_user->password)) {
						$_user->confirmPassword = $_POST['ForumMembers']['confirmPassword'];
						$_user->password = $_POST['ForumMembers']['password'];
						if(!preg_match(ForumMembers::REGEXP_PASSWORD, $_user->password)) {
							$_user->addError('password', '密码格式有误。密码可由大小写英文、数字组成，长度6－20位。');
						}
						if(!$_user->hasErrors()) {
							if($_user->validate()) {
								$status = uc_user_edit($_user->username, '', $_user->password, '', 1);
								if($status == 1) {
									$this->setPageTitle('重设密码成功 - 广州心理咨询网');
									$this->render('reset-password-success');
									return ;
								} else {
									$_user->addError('password', '修改密码失败，请稍后重试。');
								}
							}
						}
					}
				}
			}
		}
		
		$this->setPageTitle('重设密码 - 广州心理咨询网');
		$this->render('reset-password', array(
				'user' => $user,
				'_user' => isset($_user) ? $_user : new Users
			)
		);
		
	}
	
	public function actionSynlogin() {
		//Yii::app()->request->urlReferrer != '' && 
		if(Yii::app()->request->urlReferrer != '' && isset($_GET['username']) && isset($_GET['password'])) {
			$user = new ForumMembers;
			$user->username = urldecode($_GET['username']);
			$user->password = urldecode($_GET['password']);
            $status = $this->_login($user);
		}
		return ;
	}
	
	public function actionSynlogout() {
		if(Users::isLogin()) {
            Yii::app()->user->logout();
		}
	}
	
	public function actionFogotPassword() {
		$user = new ForumMembers;
		
		$messages = array();
		if(isPost() && isset($_POST['ForumMembers'])) {
			$_user = ForumMembers::model()->findByEmail((string)$_POST['ForumMembers']['email']);
			if($_user !== null) {
				if(sendMail($_user->email, $_user->username, '[广州心理咨询网]您好，'.$_user->username.'。这是您在本站重置密码的链接。', $_user->getFogotPasswordMailText())) {
					$this->setPageTitle('发送重置密码邮件成功 - 广州心理咨询网');
					$this->render('fogot-password-success');
					return ;
				}
				$messages['sendMailFailed'] = '发送邮件失败，请稍后再重试！';
			} else {
				$messages['noUser'] = '找不到该用户，请重新输入。';
			}
		}
		
		$this->setPageTitle('忘记密码 - 广州心理咨询网');
		$this->render('fogot-password', array('user' => $user, '_user' => isset($_user) ? $_user : new ForumMembers, 'messages' => $messages));
	}
	
	public function actionCaptchaValidate() {
		if(isAjax()) {
			$verifyCode = $_POST['verifyCode'];
			$cAction = new CCaptchaAction($this, 'captcha');
			echo $verifyCode === $cAction->verifyCode;
		}
	}
}
